package com.lw.leetcode.back.b;

/**
 * Created with IntelliJ IDEA.
 * 1020. 飞地的数量
 *
 * @author liw
 * @version 1.0
 * @date 2021/11/26 12:04
 */
public class NumEnclaves {

    private int[][] grid;
    private int a;
    private int b;
    public int numEnclaves(int[][] grid) {
        this. a = grid.length;
        this. b = grid[0].length;
        this.grid = grid;
        for (int i = 0; i < b; i++) {
            find(0, i);
            find(a - 1, i);
        }
        for (int i = 0; i < a; i++) {
            find(i, 0);
            find(i, b - 1);
        }
        int count = 0;
        for (int i = 1; i < a - 1; i++) {
            for (int j = 1; j < b - 1; j++) {
                if (grid[i][j] == 1) {
                    count++;
                }
            }
        }
        return count;
    }

    private void find (int x, int y) {
        if (x < 0 || x == a || y < 0 || y == b || grid[x][y] == 0) {
            return;
        }
        grid[x][y] = 0;
        find(x + 1, y);
        find(x - 1, y);
        find(x, y + 1);
        find(x, y - 1);
    }

}
